package com.jindy.module.oaWorkSummaryApply.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jindy.activiti.service.IProcessService;
import com.jindy.common.constant.Constants;
import com.jindy.common.exception.base.BaseException;
import com.jindy.common.utils.DateUtils;
import com.jindy.common.utils.SecurityUtils;
import com.jindy.common.utils.StringUtils;
import com.jindy.jpush.utils.UniJpushUtils;
import com.jindy.module.approvalRecord.domain.ApprovalRecord;
import com.jindy.module.approvalRecord.mapper.ApprovalRecordMapper;
import com.jindy.module.jpush.mapper.JpushMapper;
import com.jindy.module.oaDepartApproval.domain.SyOaDepart;
import com.jindy.module.oaDepartApproval.mapper.SyOaDepartMapper;
import com.jindy.module.oaDepartApproval.service.impl.SyOaDepartServiceImpl;
import com.jindy.module.oacopy.service.ISyOaCopyService;
import com.jindy.module.oacopyconfig.domain.SyOaCopyConfig;
import com.jindy.module.oacopyconfig.mapper.SyOaCopyConfigMapper;
import com.jindy.module.serialNum.service.ISySerialNumTService;
import com.jindy.module.syTableRecord.service.ISyTableRecordTService;
import com.jindy.system.domain.SysUserRoleDeptInfo;
import com.jindy.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jindy.module.oaWorkSummaryApply.mapper.SyOaWorkSummaryMapper;
import com.jindy.module.oaWorkSummaryApply.domain.SyOaWorkSummary;
import com.jindy.module.oaWorkSummaryApply.service.ISyOaWorkSummaryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

/**
 * 工作总结Service业务层处理
 * 
 * @author jindy
 * @date 2023-06-29
 */
@Service
public class SyOaWorkSummaryServiceImpl implements ISyOaWorkSummaryService 
{
    private static final Logger LOGGER = LoggerFactory.getLogger(SyOaWorkSummaryServiceImpl.class);

    @Autowired
    private SyOaWorkSummaryMapper syOaWorkSummaryMapper;

    @Autowired
    private IProcessService processService;

    /**
     * 抄送Service
     */
    @Resource
    private ISyOaCopyService syOaCopyService;

    /**
     * 配置表
     */
    @Resource
    private SyOaCopyConfigMapper syOaCopyConfigMapper;

    /**
     * 生成流水单号Service
     */
    @Resource
    private ISySerialNumTService serialNumTService;

    /**
     * 生成流水单号Service
     */
    @Resource
    private ApprovalRecordMapper approvalRecordMapper;

    /**
     * 用户Service
     */
    @Resource
    private ISysUserService sysUserService;

    /**
     * 设备Mapper
     */
    @Resource
    private JpushMapper jpushMapper;

    /**
     * 存储表Service
     */
    @Resource
    private ISyTableRecordTService iSyTableRecordTService;


    /**
     * 查询工作总结
     * 
     * @param id 工作总结主键
     * @return 工作总结
     */
    @Override
    public SyOaWorkSummary selectSyOaWorkSummaryById(Long id)
    {
        return syOaWorkSummaryMapper.selectSyOaWorkSummaryById(id);
    }

    /**
     * 查询工作总结列表
     * 
     * @param syOaWorkSummary 工作总结
     * @return 工作总结
     */
    @Override
    public List<SyOaWorkSummary> selectSyOaWorkSummaryList(SyOaWorkSummary syOaWorkSummary)
    {
        if (!SecurityUtils.isAdmin(SecurityUtils.getLoginUser().getUser().getUserId())) {
            syOaWorkSummary.setCreateBy(SecurityUtils.getUsername());
        }
        List<SyOaWorkSummary> list = syOaWorkSummaryMapper.selectSyOaWorkSummaryList(syOaWorkSummary);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(item -> {
                try {
                    processService.richProcessField(item);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }

        System.out.println("1sd5v1s5v");
        for (int i=0;i<list.size();i++){
            System.out.println("-----"+i+"-----");
            System.out.println(list.get(i).getTaskId());
            System.out.println(list.get(i).getTaskName());
        }
        return list;
//        return syOaWorkSummaryMapper.selectSyOaWorkSummaryList(syOaWorkSummary);
    }

    /**
     * 新增工作总结
     * 
     * @param syOaWorkSummary 工作总结
     * @return 结果
     */
    @Override
    public int insertSyOaWorkSummary(SyOaWorkSummary syOaWorkSummary)
    {
        // 生成流水单号
        String serialNum = serialNumTService.generateSerialNum("GZZJSP");
        if (StringUtils.isBlank(serialNum)) {
            throw new BaseException("新增工作总结审批-获取工作总结单号失败");
        }
        //获取申请人信息
        Long userId=SecurityUtils.getLoginUser().getUser().getUserId();
        syOaWorkSummary.setApplyUserId(userId.toString());
        syOaWorkSummary.setApplyUserName(SecurityUtils.getLoginUser().getUser().getUserName());

        //获取申请时间
        syOaWorkSummary.setApplyTime(DateUtils.getNowDate());

        syOaWorkSummary.setSerialNum(serialNum);
        syOaWorkSummary.setBusinessStatus(Constants.DRAFT);
        syOaWorkSummary.setCreateTime(DateUtils.getNowDate());
        iSyTableRecordTService.saveEntityAndTable(syOaWorkSummary,serialNum);
        return syOaWorkSummaryMapper.insertSyOaWorkSummary(syOaWorkSummary);
    }

    /**
     * 修改工作总结
     * 
     * @param syOaWorkSummary 工作总结
     * @return 结果
     */
    @Override
    public int updateSyOaWorkSummary(SyOaWorkSummary syOaWorkSummary)
    {
        syOaWorkSummary.setUpdateTime(DateUtils.getNowDate());
        return syOaWorkSummaryMapper.updateSyOaWorkSummary(syOaWorkSummary);
    }

    /**
     * 批量删除工作总结
     * 
     * @param ids 需要删除的工作总结主键
     * @return 结果
     */
    @Override
    public int deleteSyOaWorkSummaryByIds(Long[] ids)
    {
        return syOaWorkSummaryMapper.deleteSyOaWorkSummaryByIds(ids);
    }

    /**
     * 删除工作总结信息
     * 
     * @param id 工作总结主键
     * @return 结果
     */
    @Override
    public int deleteSyOaWorkSummaryById(Long id)
    {
        return syOaWorkSummaryMapper.deleteSyOaWorkSummaryById(id);
    }

    /**
     * 提交申请
     *
     * @param syOaWorkSummary
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void submitApply(SyOaWorkSummary syOaWorkSummary) throws Exception {
        // 初始化值
        Map<String, Object> variables = createVariables(syOaWorkSummary);
        // 启动流程
        processService.submitApply(syOaWorkSummary, "summary", variables);
        // 添加抄送人
        syOaCopyService.addCopyUsers("GZZJSP", syOaWorkSummary.getId());
        //新增审批记录
        List<Long> longs = addApprovalRecord(syOaWorkSummary, variables);
        // 通知审批人
        sendApproveMessage(longs);
        syOaWorkSummary.setBusinessStatus(Constants.APPROVE);
        syOaWorkSummary.setTaskId("-1");
        syOaWorkSummary.setTaskName("已结束");
        updateSyOaWorkSummary(syOaWorkSummary);
    }

    /**
     * 获取审批记录对象
     *
     * @param syOaWorkSummary
     * @return
     */
    private ApprovalRecord getApprovalRecord(SyOaWorkSummary syOaWorkSummary) {
        ApprovalRecord approvalRecord = new ApprovalRecord();
        approvalRecord.setSerialNum(syOaWorkSummary.getSerialNum());
        approvalRecord.setUserId(Long.valueOf(syOaWorkSummary.getApplyUserId()));
        approvalRecord.setOrderId(syOaWorkSummary.getId());
        approvalRecord.setUserName(syOaWorkSummary.getApplyUserName());
        approvalRecord.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
        approvalRecord.setUpdateBy(syOaWorkSummary.getApplyUserName());
        approvalRecord.setCreateBy(syOaWorkSummary.getApplyUserName());
        approvalRecord.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
        return approvalRecord;
    }

    /**
     * 新增审批记录
     * @param syOaWorkSummary
     * @param map
     * @return
     */
    private List<Long> addApprovalRecord(SyOaWorkSummary syOaWorkSummary, Map<String, Object> map) {
        List<Long> list = new ArrayList<>();
        int sequence = 1;
        //  发起人
        ApprovalRecord firstApprovalRecord = getApprovalRecord(syOaWorkSummary);
        firstApprovalRecord.setSequence(sequence);
        firstApprovalRecord.setApprovalStatus(Constants.COMPLETED);
        firstApprovalRecord.setTypeOperation(Constants.AGREE);
        firstApprovalRecord.setBusinessStatus(Constants.APPROVE);
        firstApprovalRecord.setApproverId(Long.valueOf(syOaWorkSummary.getApplyUserId()));
        firstApprovalRecord.setApproverName(syOaWorkSummary.getApplyUserName());
        approvalRecordMapper.insertApprovalRecord(firstApprovalRecord);
        return list;
    }

    /**
     * 逻辑流初始化
     *
     * @param syOaWorkSummary
     * @return
     */
    public Map<String, Object> createVariables(SyOaWorkSummary syOaWorkSummary) {
        Map<String, Object> var = new HashMap<>(500);

        return var;
    }

    /**
     * 给审批人推送消息
     * @param addJpushList
     */
    private void sendApproveMessage(List<Long> addJpushList) {
        try {
            List<String> addRegIds = jpushMapper.selectRegistrationIdsByUserIds(addJpushList);
            if (!CollectionUtils.isEmpty(addRegIds)){
                UniJpushUtils.sendApproveMessage(addRegIds);
            }
        } catch (Exception e) {
            LOGGER.error("离职审批审批人推送通知失败",e);
        }
    }
}
